package com.ym.b2b.payment.controller.bocPay.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.ym.b2b.payment.controller.bocPay.BOCV1Params;
import com.ym.b2b.payment.controller.bocPay.security.Base64;
import com.ym.b2b.payment.controller.bocPay.security.PKCSTool;

public class DocumentUtil {
	static Logger logger = Logger.getLogger(DocumentUtil.class.getName());

	public String getRequestPlainText(BOCV1Params bp) throws Exception {
		String merchantNo = bp.getMerchantNo();
		String orderNo = bp.getOrderNo();
		String currency = bp.getCurrency();
		String amount = bp.getAmount();
		String orderTime = bp.getOrderTime();
		String orderNote = bp.getOrderNote();
		String backNotifyUrl = bp.getBackNotifyUrl();
		String closeTime = bp.getCloseTime();
		String subMerchantInfo = bp.getSubMerchantInfo();

		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String requestTime = sdf.format(date);

		// 执行报文处理
		DocumentBuilderFactory documentbuilderfactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder documentbuilder = documentbuilderfactory
				.newDocumentBuilder();
		Document document = documentbuilder.newDocument();
		Element element = document.createElement("request");
		Element element1 = document.createElement("head");
		Element element2 = document.createElement("requestTime");
		Element element3 = document.createElement("body");
		Element element4 = document.createElement("orderNo");
		Element element5 = document.createElement("currency");
		Element element6 = document.createElement("amount");
		Element element7 = document.createElement("orderTime");
		Element element8 = document.createElement("orderNote");
		Element element9 = document.createElement("backNotifyUrl");
		Element element10 = document.createElement("closeTime");
		Element element11 = document.createElement("subMerchantInfo");
		element.setAttribute("version", "1.0");
		document.appendChild(element);
		element.appendChild(element1);
		element.appendChild(element3);
		element1.appendChild(element2);
		element2.setTextContent(requestTime);
		element3.appendChild(element4);
		element4.setTextContent(orderNo);
		element3.appendChild(element5);
		element5.setTextContent(currency);
		element3.appendChild(element6);
		element6.setTextContent(amount);
		element3.appendChild(element7);
		element7.setTextContent(orderTime);
		if (orderNote != null && orderNote.trim().length() != 0) {
			element3.appendChild(element8);
			element8.setTextContent(orderNote);
		}
		if (backNotifyUrl != null && backNotifyUrl.trim().length() != 0) {
			element3.appendChild(element9);
			element9.setTextContent(backNotifyUrl);
		}
		if (closeTime != null && closeTime.trim().length() != 0) {
			element3.appendChild(element10);
			element10.setTextContent(closeTime);
		}
		if (subMerchantInfo != null && subMerchantInfo.trim().length() != 0) {
			element3.appendChild(element11);
			element11.setTextContent(subMerchantInfo);
		}

		String requestPlainText = XmlUtil.createPrettyFormat(document).trim();
		logger.debug("---------- NB2BRecvOrder send message before base64 encoded ----------");
		logger.debug("[merchantNo]=[" + merchantNo + "]");
		logger.debug("[version]=[" + Constants.B2B_DIRECT_VERSION + "]");
		logger.debug("[messageId]=[" + Constants.MessageId.NB2BRecvOrder + "]");
		logger.debug("[security]=[" + Constants.SECURITY + "]");
		logger.debug("[message]=[" + requestPlainText + "]");

		return requestPlainText;
	}

	public Map<String,String> getRequestMap(BOCV1Params bp) throws Exception {
		Map<String,String> map = new HashMap<String,String>();
		// 对message原文进行加签
		// 获取私钥证书
		PKCSTool tool = PKCSTool.getSigner(bp.getSignKeyFile(),
				bp.getSignkeyPassword(),
				bp.getSignkeyPassword(), "PKCS7");
		// 签名
		byte requestPlainTextByte[] = getRequestPlainText(bp).getBytes("UTF-8");
		String requestSignature = tool.p7Sign(requestPlainTextByte);
		// 上送域进行BASE64编码
		String requestMessage = Base64.encode(requestPlainTextByte);
		String requestMerchantNo = Base64.encode(bp.getMerchantNo().getBytes(
				"UTF-8"));
		String requestVersion = Base64.encode(Constants.B2B_DIRECT_VERSION.getBytes("UTF-8"));
		String requestMessageId = Base64.encode(Constants.MessageId.NB2BRecvOrder.getBytes("UTF-8"));
		String requestSecurity = Base64.encode(Constants.SECURITY.getBytes("UTF-8"));
		String action = bp.getServerUrl();
		map.put("merchantNo", requestMerchantNo);
		map.put("version", requestVersion);
		map.put("messageId", requestMessageId);
		map.put("security", requestSecurity);
		map.put("signature", requestSignature);
		map.put("message", requestMessage);
		map.put("action", action);
		return map;
	}
	
	public Map<String,String> getRequestMapForQuery(BOCV1Params bp) throws Exception {
		Map<String,String> map = new HashMap<String,String>();
		// 对message原文进行加签
		// 获取私钥证书
		PKCSTool tool = PKCSTool.getSigner(bp.getSignKeyFile(),
				bp.getSignkeyPassword(),
				bp.getSignkeyPassword(), "PKCS7");
		// 签名
		byte requestPlainTextByte[] = getRequestPlainTextForQuery(bp).getBytes("UTF-8");
		String requestSignature = tool.p7Sign(requestPlainTextByte);
		// 上送域进行BASE64编码
		String requestMessage = Base64.encode(requestPlainTextByte);
		String requestMerchantNo = Base64.encode(bp.getMerchantNo().getBytes(
				"UTF-8"));
		String requestVersion = Base64.encode(Constants.B2B_DIRECT_VERSION.getBytes("UTF-8"));
		String requestMessageId = Base64.encode(Constants.MessageId.NB2BQueryOrder.getBytes("UTF-8"));
		String requestSecurity = Base64.encode(Constants.SECURITY.getBytes("UTF-8"));
		String action = bp.getServerUrl();
		map.put("merchantNo", requestMerchantNo);
		map.put("version", requestVersion);
		map.put("messageId", requestMessageId);
		map.put("security", requestSecurity);
		map.put("signature", requestSignature);
		map.put("message", requestMessage);
		map.put("action", action);
		return map;
	}
	
	public String getRequestPlainTextForQuery(BOCV1Params bp) throws Exception {
		String orderNo = bp.getOrderNo();
		
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String requestTime = sdf.format(date);

		// 执行报文处理
		DocumentBuilderFactory documentbuilderfactory = DocumentBuilderFactory
				.newInstance();
		DocumentBuilder documentbuilder = documentbuilderfactory
				.newDocumentBuilder();
		Document document = documentbuilder.newDocument();
		Element element = document.createElement("request");
		Element element1 = document.createElement("head");
		Element element2 = document.createElement("requestTime");
		Element element3 = document.createElement("body");
		Element element4 = document.createElement("orderNo");
		element.setAttribute("version", "1.0");
		document.appendChild(element);
		element.appendChild(element1);
		element.appendChild(element3);
		element1.appendChild(element2);
		element2.setTextContent(requestTime);
		element3.appendChild(element4);
		element4.setTextContent(orderNo);
		

		String requestPlainText = XmlUtil.createPrettyFormat(document).trim();
		logger.debug("[message]=[" + requestPlainText + "]");
		return requestPlainText;
	}
}
